package com.publicize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.publicize.commom.commonutils.JwtUtils;
import com.publicize.commom.commonutils.MD5;
import com.publicize.commom.servicebase.exception.MyException;
import com.publicize.entity.User;
import com.publicize.entity.Vo.UserLogin;
import com.publicize.mapper.UserMapper;
import com.publicize.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author bs
 * @since 2021-03-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
//用户登录
    @Override
    public String userLogin(UserLogin user) {
        //判断用户名密码是否为空
        if(StringUtils.isEmpty(user) ||StringUtils.isEmpty(user.getPassword())) throw new MyException("用户名或者密码并不能为空",201);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        //判断用户名密码是否存在
        queryWrapper.eq("email",user.getEmail());
        queryWrapper.eq("password", MD5.encrypt(user.getPassword()));
        User userOne = baseMapper.selectOne(queryWrapper);
        if(userOne==null) throw new MyException("邮箱或密码错误",201);
        String jwtToken = JwtUtils.getJwtToken(userOne.getId(), userOne.getUsername());
        return jwtToken;
    }
//用户注册
    @Override
    public void userRegister(User user) {
        //判断用户是否为空
        if(StringUtils.isEmpty(user)) throw new MyException("注册资料不能为空",201);
        //根据邮箱判断用户是否已注册
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",user.getEmail());
        List<User> users = baseMapper.selectList(queryWrapper);
        if(users.size()>0) throw new MyException("该用户已注册",201);
        //插入用户表并加密密码
        user.setPassword(MD5.encrypt(user.getPassword()));
        int insert = baseMapper.insert(user);
        if(insert!=1) throw new MyException("注册失败",201);
    }

    @Override
    public void deleteAvatar(String fileName) {
        System.out.println(fileName);
        File file=new File(fileName);

        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
            } else {
                throw new MyException("删除单个文件" + fileName + "失败！",201);
            }
        } else {
            throw new MyException("删除单个文件失败：" + fileName + "不存在！",201);
        }
    }
}
